package cn.wjzhang.middle.utils;


import cn.wjzhang.middle.modules.global.beans.response.ValidateResult;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 校验工具类
 * @author
 * @date
 */
public class ValidatorUtil {
	
	private static Validator validator;
	
	static {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		validator = factory.getValidator();
	}
	
	public static <T> ValidateResult validator(T object) {
		ValidateResult result = new ValidateResult();
		if(object == null) {
			result.setResult(false);
			result.setErrMsg(new String[] {"输入的待校验对象不能为空"});
		}else {
			Set<ConstraintViolation<T>> violations = validator.validate(object);
			if(violations.isEmpty()) {
				result.setResult(true);
			}else {
				List<String> messageList = new ArrayList<String>();
				for(ConstraintViolation<T> violation:violations) {
					messageList.add(violation.getMessage());
				}
				result.setResult(false);
				result.setErrMsg(messageList.toArray(new String[0]));
			}
		}
		return result;
	}
	
}
